#define _CRT_SECURE_NO_WARNINGS 1
#include"string.h"

namespace zhaojiahao
{
	void string::reserve(size_t n)
	{
		if (n>_capacity)
		{
			char*tmp= new char[n + 1];
			strcpy(tmp, _str);
			delete[] _str;
			_str = tmp;
			_capacity = n;
		}
	}

	void string::push_back(char ch)
	{
		if (_size == _capacity)
		{
			reserve(_capacity == 0 ? 4: 2 * _capacity);
		}
		_str[_size] = ch;
		_size++;
		_str[_size] = '\0';
	}
	void string::append(const char* str)
	{
		int len = strlen(str);
		if (len + _size > _capacity)
		{
			reserve(len + _size>2*_capacity? len+_size: 2 * _capacity);
		}
		strcat(_str, str);
		_size += len;
	}

	string& string::operator+=(char ch)
	{
		if (_size == _capacity)
		{
			reserve(_capacity == 0 ? 4 : 2 * _capacity);
		}

		_str[_size] = ch;
		_size++;
		_str[_size] = '\0';
		return *this;
	}
	string& string::operator+=(const char* str)
	{
		append(str);
		return *this;
	}
	void string::insert(size_t pos, char ch)
	{
		assert(pos < _size);
		if (_size == _capacity)
			reserve(_capacity == 0 ? 4 : 2 * _capacity);
		size_t end = _size;
		while (pos<end)
		{
			_str[end] = _str[end - 1];
			end--;
		}
		_str[pos] = ch;

	}

	void string::insert(size_t pos, const char* str)
	{
		assert(pos < _size);
		int len = strlen(str);
		if (len + _size > _capacity)
			reserve(len + _size > 2 * _capacity ? len + _size : 2 * _capacity);

		size_t end = _size+len;
		while (pos+len-1<end)
		{
			_str[end] = _str[end - len];
			end--;
		}
		for (int i = 0; i < len; i++)
		{
			_str[i + pos] = str[i];
		}
		_size += len;
	}
}